<?php
/**
 * Description of ServiceGenerator
 *
 * @author BloumGenerator
 */
class ServiceGenerator {

    private $tableMeta;
    private $parentTbMeta;
    private $templateService;
    private $attPK;
    private $params;

    function __construct($tableMeta, $params) {
        $this->tableMeta = $tableMeta;
        $this->params = $params;
        $this->parentTbMeta = null;

        if(!file_exists(Constantes::$TEMPLATES_SERVICE_DIR."Service.bloum"))
            throw new Exception ("Template Service Not Found!!!");

        $this->templateService = file_get_contents(Constantes::$TEMPLATES_SERVICE_DIR."Service.bloum");
        $this->searchPK();
        $this->searchParent();

    }

    public function searchPK(){
        $numExt = 0;
        foreach ($this->tableMeta->getFKReferences() as $fk) {
            if($fk->isExtends()){
                $numExt++;
                $this->parentTbMeta = $fk->getTableReference();
            }
        }
        if($numExt > 1){
            throw new Exception("Erro, Herança Multipla Não Suportado!!!");
        }
    }

    public function searchParent(){
        foreach ($this->tableMeta->getAttributes() as $att) {
            if($att->isPrimaryKey()){
                $this->attPK[$att->getName()] = $att;
            }
        }
    }

    public function generate(){
        $this->templateService = str_replace(Constantes::$TPL_BEAN_NAME_UPPER, ucfirst($this->tableMeta->getName()), $this->templateService);
        $this->templateService = str_replace(Constantes::$TPL_BEAN_NAME_LOWER, lcfirst($this->tableMeta->getName()), $this->templateService);

        $this->generatePkValues();
        $this->generateListParam();
        
        return $this->templateService;
    }
    
    public function generatePkValues(){

        $tableName = $this->tableMeta->getName();
        
        $pkInitParam = "";        
        $pkIfTest = "";
        $pkList = "";
        $pkTotal = "";

        $attrsKeys = array_keys($this->attPK);

        for ($i = 0; $i < count($attrsKeys); $i++) {
            $att = $this->attPK[$attrsKeys[$i]];
            $name = $att->getName();
            
            $pkList .= "$".$name;
            $pkInitParam .= "$".$name." = -1";            
            $pkIfTest .= " $".$name." == null || $".$name." <= 0 ";
            $pkTotal = $name;
            
            if($i < ( count($this->attPK)-1 )){
                $pkList .= ", ";
                $pkIfTest .= "\n\t\t\t || ";
                $pkInitParam .= ", ";                
            }
        }

        $this->templateService = str_replace(Constantes::$TPL_SERVICE_PK_IF_TEST, $pkIfTest, $this->templateService);        
        $this->templateService = str_replace(Constantes::$TPL_SERVICE_PK_INIT_PARAM, $pkInitParam, $this->templateService);
        $this->templateService = str_replace(Constantes::$TPL_SERVICE_PK_LIST, $pkList, $this->templateService);
        $this->templateService = str_replace(Constantes::$TPL_SERVICE_PK_TOTAL, $pkTotal, $this->templateService);
    }
    
    public function generateListParam(){
        $attrs = $this->tableMeta->getAttributes();

        if($this->parentTbMeta != null && count($this->parentTbMeta->getAttributes()) > 0)
            $attrs = array_merge ($attrs,$this->parentTbMeta->getAttributes());

        $attrsKeys = array_keys($attrs);
        $tableName = $this->tableMeta->getName();
        $listParam = "";
        $listParamInit = "";        

        for ($i = 0; $i < count($attrsKeys); $i++) {
            $name = $attrsKeys[$i];

            if(!$attrs[$name]->isPrimaryKey() && $attrs[$name]->isImportant()){
                
                if(strlen($listParam) > 0){
                    $listParam .= ", ";                    
                }
                
                if(strlen($listParamInit) > 0){
                    $listParamInit .= ", ";                    
                }
                
                $listParam .= "$$name";

                $type = $attrs[$name]->getType();
                $default = $attrs[$name]->getDefault();

                $value = '""';
                if(Util::isTypeNumeric($type)){
                    $value = "-1";
                    if(strlen($default))
                        $value = $default;

                }else{
                    $value = "\"\"";
                    
                }

                $listParamInit .= "$".$name." = ".$value;
                
            }

        }

        $this->templateService = str_replace(Constantes::$TPL_LIST_PARAM_INIT, $listParamInit, $this->templateService);
        $this->templateService = str_replace(Constantes::$TPL_LIST_PARAM, $listParam, $this->templateService);        
        $this->templateService = str_replace(",,", ",", $this->templateService); #gambiarra        
    }

    public function generateFile($generate = true){
        if($generate)
            $this->generate();

        $dirService = "temp_gen/".$this->params[Constantes::$PARAM_PROJECT_NAME]."/service/";

        if(!file_exists($dirService))
            mkdir ($dirService, 0755,true);

        $fp = fopen($dirService.ucfirst($this->tableMeta->getName())."Service.class.php", "w+");
        fwrite($fp, $this->templateService);
        fclose($fp);
    }
}

?>
